from  etguiimpl import *
import etguiimpl
from types import *
import CmdNo
PotGuiVObj=ETPotGuiVObj
def PotGuiTextField(slot,field,update=0):
	return ETPotGuiTextField(slot,field,update)
def PotGuiSplitTextField(slot,field,split_char=' ',remove_empty=1,update=0):
	return ETPotGuiSplitTextField(slot,field,split_char,remove_empty,update)
def PotGuiIntField(slot,field,update=0):
	return ETPotGuiIntField(slot,field,update)
def PotGuiToggleButton(path,label):
	if type(label)==StringType:
		return ETPotGuiToggleButton(path,label)
	else:
		return ETPotGuiToggleButton(path,'',label)
PotGuiModel=SimplePotGuiModel
EditPotGuiModel=ETEditPotGuiModel
PotGuiSubModel=ETPotGuiSubModel
PotGuiActionButton=ETPotGuiActionButton
PotGuiVObjDefaultDecorator=ETPotGuiVObjDefaultDecorator
PotGuiEnabler=ETPotGuiVObjEnableDecorator
class TraceModelObserver:
	def __init__(self,what):
		self.what=what
	def __call__(self,model,path):
		print "TraceModelObserver:"+self.what+str((model,path))

class AbstrPyModel(PyPotGuiModel):
	def __init__(self):
		PyPotGuiModel.__init__(self)
		self.SetPyImpl(self)
	def DoSetValue(self, path,value):
		return None
	def DoGetValue(self, path):
		return None
	def DoIsValueChangable(self, path):
		return 1
	def DoGetIndex(self,path):
		raise RuntimeError, "Not implemented:DoGetIndex"
		return []
	def DoRemoveAt(self,path):
		raise RuntimeError, "Not implemented:DoRemoveAt"
		return None
	def DoCanRemoveAt(self,path):
		raise RuntimeError, "Not implemented:DoCanRemoveAt"
		return 1
	def DoCancel(self):
		pass
	def DoApply(self):
		pass
	def DoCanApply(self):
		return 1
	def DoMarkSlot(self,path,on):
		raise RuntimeError, "Not implemented:DoMarkSlot"
		pass

class DictPyModel(AbstrPyModel):
	def __init__(self,dict=None):
		if dict is None:
			dict={}
		self.dict=dict
		AbstrPyModel.__init__(self)
	def DoSetValue(self, path,value):
		old=self.dict.get(path,None)
		self.dict[path]=value
		return old
	def DoGetValue(self, path):
		return self.dict.get(path,None)

NULL="NULL"
def IsNULL(v):
	if v is None:
		return 1
	if v == NULL:
		return 1
	try:
		return v.this==NULL
	except:
		return 0
#----------------------------------------
# Helpers
#----------------------------------------
gCurrID=5000
def newID():
	global gCurrID
	id=gCurrID
	gCurrID=gCurrID+1
	return id

def Add(self,items,factory=None):
	id=gCurrID
	if factory is None:
		factory=TextItem
	for i in range(len(items)):
		vop=items[i]
		if type(vop)==StringType:
			vop=factory(newID(),vop)
		self.Add(vop)
	#self.Update()
	return id
def AddToolTip(obj,tooltip):
	if tooltip:
		if type(tooltip) is StringType:
			tooltip=MultilineTextItem(tooltip)
		obj.AddToolTip(tooltip)

class Kwds:
	def __init__(self,kwds,**defaults):
		set=setattr
		defaults['flags']=None
		for n,v in defaults.items():
			set(self,n,v)
		for n,v in kwds.items():
			defaults[n]
			set(self,n,v)
	def Setup(self,obj):
		if self.flags is not None:
			obj.SetFlag(self.flags)
		try:
			AddToolTip(obj,self.tooltip)
		except AttributeError:
			pass
 
#----------------------------------------

def Point(x,y=None):
	if y is None:
		y=x
	return (x,y)
def Rectangle(origin,extent):
	return origin+extent

gPoint_1=Point(-1)
gPoint0=Point(0)
gPoint1=Point(1)
gPoint2=Point(2)
gPoint3=Point(3)
gPoint4=Point(4)
gPoint5=Point(5)
gPoint6=Point(6)
gPoint7=Point(7)
gPoint8=Point(8)
gPoint10=Point(10)
gPoint16=Point(16)
gPoint32=Point(32)
gPoint64=Point(64)
gBorder=Point(4,1)

class TextItem(ETTextItem):
	def __init__(self,id=None,name=None,font=gSysFont,flags=None,border=None) :
		if type(id) == StringType and name is None:
			name=id
			id=-1
		if id is None:
			id=-1
		ETTextItem.__init__(self,id,name,font)
		if border is not None:
			self.SetBorder(border)
		if flags is not None:
			self.SetFlag(flags)

class StyledTextItem(ETStyledTextItem):
	def __init__(self,id=None,name=None,font=gSysFont,flags=None,border=None, ink=None) :
		if type(id) == StringType and name is None:
			name=id
			id=-1
		if id is None:
			id=-1
		if ink:
			ETStyledTextItem.__init__(self,id,name,font,ink)
		else:
			ETStyledTextItem.__init__(self,id,name,font)
		if border is not None:
			self.SetBorder(border)
		if flags is not None:
			self.SetFlag(flags)
class IntField(ETIntField):
	def __init__(self,id=None,val=0,mainval=None,maxval=None,flags=eVObjHFixed):
		args=(self,id,val,mainval,maxval)
		if maxval is None:
			args=args[:-1]
		if mainval is None:
			args=args[:-1]
		apply(ETIntField.__init__,args)
		if flags is not None:
			self.SetFlag(flags)
class FloatField(ETFloatField):
	def __init__(self,id=None,val=0,mainval=None,maxval=None,flags=eVObjHFixed):
		ETFloatField.__init__(self,id,val,mainval,maxval)
		if flags is not None:
			self.SetFlag(flags)
 
 
class RadioButton(ETRadioButton):
	def __init__(self,id,item=None):
		if type(id)!=IntType:
			item=id
			id=-1
		if type(item)==StringType:
			item=TextItem(item)
		ETRadioButton.__init__(self,id,item)
class ToggleButton(ETToggleButton):
	def __init__(self,id,item=None):
		if type(id)!=IntType:
			item=id
			id=-1
		if type(item)==StringType:
			item=TextItem(item)
		ETToggleButton.__init__(self,id,item)

class ControlDecoratorForw(VObjectPtr):
	def __init__(self,inner,func,*args):
		self.inner=inner
		this = apply(etguiimplc.ControlDecorator,(inner.this,func,)+args)
		VObjectPtr.__init__(self,this)
	def __getattr__(self,name):
		return getattr(self.inner,name)

def ActionButton(id=None,item=None,default=0,action=None,tooltip=None):
	"""action is a parameter-less function, called when the button is pressed"""
	if type(id)!=IntType:
		item=id
		id=-1
	if type(item)==StringType:
		item=TextItem(item)
	button=ETActionButton(id,item,default)
	if tooltip:
		AddToolTip(button,tooltip)
	if action is None:
		return button
	else:
		def func(id,part,v,action=action): 
			# Function that keeps a reference to action, which is calles
			# A simple trick to emulate closure
			action()
		return ControlDecoratorForw(button,func)
def PseudoTabPage(label,inner,action=None,tooltip=None):
	"""action is a parameter-less function, called when the button is pressed"""
	if type(label)==StringType:
		item=TextItem(label)
	page=ETPseudoTabPage(-1,label,inner)
	if tooltip:
		AddToolTip(button,tooltip)
	if action is None:
		return page
	else:
		def func(id,part,v,action=action): 
			# Function that keeps a reference to action, which is calles
			# A simple trick to emulate closure
			if part==CmdNo.cPartAction:
				action()
		ctrl=ControlDecoratorForw(page,func,1) # observe the object
		return page

class Filler(ETFiller):
	def __init__(self,arg0=gPoint0,*args,**kwds) :
		apply(ETFiller.__init__,(self,arg0)+args)
		k=Kwds(kwds,flags=None)
		k.Setup(self)

class VBox(ETVBox):
	def __init__(self,**kwds) :
		k=Kwds(kwds,gap=gBorder,align=eVObjH,items=())
		ETVBox.__init__(self,k.gap,k.align)
		Add(self,k.items)
		k.Setup(self)

class HBox(ETHBox):
	def __init__(self,**kwds) :
		k=Kwds(kwds,gap=gBorder,align=eVObjH,items=())
		ETHBox.__init__(self,k.gap,k.align)
		Add(self,k.items)
		k.Setup(self)

class ManyOfCluster(ETManyOfCluster):
	def __init__(self,*items) :
		ETManyOfCluster.__init__(self)
		self.SetId(Add(self,items,ToggleButton))

class OneOfCluster(ETOneOfCluster):
	def __init__(self,*items) :
		ETOneOfCluster.__init__(self)
		self.SetId(Add(self,items,RadioButton))
		self.SetItemOn(self.GetId())

class BorderItem(ETBorderItem):
	def __init__(self,title,inner,showRect=1):
		if type(title)==StringType:
			title=TextItem(-1,title)
		ETBorderItem.__init__(self,title,inner,showRect)

def MiddleFormTextItem(i,label):
	"""Returns textitem which is right aligned."""
	#print label
	return AlignBox(eVObjHRight,
			flags=eVObjHFixed,
			inner=TextItem(i,label,flags=eVObjHFixed,border=gPoint0), 
	)
def FormTextItem(i,label):
	"""Returns textitem without border"""
	return TextItem(i,label,flags=eVObjHFixed,border=Point(0,2))
class AlignBox(ETAlignBox):
	def __init__(self,align,inner,ink=gInkNone,flags=None):
		ETAlignBox.__init__(self,align,inner,ink)
		if flags is not None:
			self.SetFlag(flags)
 
class Form(ETForm):
	def __init__(self,**kwds) :
		k=Kwds(kwds,gap=Point(4,0),align=0,items=(),middle=0)
		ETForm.__init__(self,-1,k.align,k.gap)
		if k.middle:
			Add(self,k.items,MiddleFormTextItem)
		else:
			Add(self,k.items,FormTextItem)
 
		if k.align !=0:
			self.SetAlign(k.align)
		k.Setup(self)

class HExpander(ETHExpander):
	def __init__(self,**kwds) :
		k=Kwds(kwds,gap=gBorder, items=())
		ETHExpander.__init__(self,k.gap)
		Add(self,k.items)
		k.Setup(self)

class VExpander(ETVExpander):
	def __init__(self,**kwds) :
		k=Kwds(kwds,gap=gBorder, items=())
		ETVExpander.__init__(self,k.gap)
		Add(self,k.items)
		k.Setup(self)
class VSplitExpander(ETSniffExpander):
	def __init__(self,**kwds) :
		k=Kwds(kwds,gap=gBorder,align=eVObjH, items=())
		ETSniffExpander.__init__(self,eVert,k.gap)
		Add(self,k.items)
		k.Setup(self)
class HSplitExpander(ETSniffExpander):
	def __init__(self,**kwds) :
		k=Kwds(kwds,gap=gBorder,align=eVObjH, items=())
		ETSniffExpander.__init__(self,eHor,k.gap)
		Add(self,k.items)
		k.Setup(self)
class VSplitter(ETSniffSplitter):
	def __init__(self,**kwds) :
		k=Kwds(kwds,gap=gBorder,align=eVObjH, items=())
		ETSniffSplitter.__init__(self,eVert,k.gap,k.items[0])
		Add(self,k.items[1:])
		k.Setup(self)
class HSplitter(ETSniffSplitter):
	def __init__(self,**kwds) :
		k=Kwds(kwds,gap=gBorder,align=eVObjH, items=())
		ETSniffSplitter.__init__(self,eHor,k.gap,k.items[0])
		Add(self,k.items[1:])
		k.Setup(self)

class Menu(ETMenu):
	def __init__(self,**kwds) :
		k=Kwds(kwds,id=newID(),title='',dimall=1, resetall=1,rows=0,cols=1,items=())
		ETMenu.__init__(self,k.id,k.title,k.dimall,k.resetall,k.rows,k.cols)
		Add(self,k.items,self.MakeMenuItem)
		k.Setup(self)
	def Add(self,item):
		self.Append(item)
	def Update(self):
		pass
 
class PopupButton(ETPopupButton):
	def __init__(self,*args,**kwds) :
		k=Kwds(kwds,id=newID(), defaultid=-1, items=(),menu=None,flags=eVObjHFixed)
		if k.menu is None:
			items=tuple(k.items)+args
			k.menu=Menu(resetall=1,dimall=0,items=items)
 
		ETPopupButton.__init__(self,k.id,k.defaultid,k.menu)
		k.Setup(self)
class CollectionView(ETCollectionView):
	def __init__(self,control=None,coll=NULL,flags=eCVDefault, rows=0, cols=1):
		ETCollectionView.__init__(self,control,coll,flags,rows,cols)
	def SelectItem(self,i):
		if i<0:
			self.SetSelection((0,0,0,0))
		else:
			self.SetSelection((0,i,1,1))
	def SelectedItem(self):
		x,y,w,h=self.GetSelection()
		if w>0:
			return x
		else:
			return -1
	def DeleteItem(self,i):
		coll=self.GetCollection()
		if i<0 or i>=coll.Size():
			raise IndexError,i
		SafeDelete(coll.RemoveAt(i))
	def AddItem(self,item,i=-1):
		coll=self.GetCollection()
		if i<0 or i>coll.Size():
			i=coll.Size()
		coll.AddAt(item,i)
class MultiCollView(ETMultiSelCollView):
	def __init__(self,items=()):
		coll=OrdCollection()
		for item in items:
			coll.Add(item)
		self.coll=coll
		ETMultiSelCollView.__init__(self,self,coll,eCVExpandRows|eCVDrawFocus)
	def __call__(self,*args):
		self.SelectionChanged()
	def SelectionChanged(self):
		pass
	def AddItem(self,item):
		self.coll.Add(item)
	def DeleteItem(self,i):
		coll=self.GetCollection()
		if i<0 or i>=coll.Size():
			raise IndexError,i
		SafeDelete(coll.RemoveAt(i))
	def FreeAllItems(self):
		self.coll=OrdCollection()
		self.SetCollection(self.coll)
	def ReplaceItems(self,items):
		self.coll=OrdCollection()
		for item in items:
			self.coll.Add(item)
		self.SetCollection(self.coll)
	def NSelected(self):
		return self.GetSelection().Size()
	def GetSelectedItems(self):
		result=[]
		selection=self.GetSelection()
		for i in range(selection.Size()):
			result.append(selection.At(i))
		return result
	def GetSelectedNumbers(self):
		result=[]
		items={}
		for i in self.GetSelectedItems():
			items[i.this]=1
		for i in range(self.coll.Size()):
			item=self.coll.At(i)
			if items.has_key(item.this):
				result.append(i)
		return result

class Scroller(ETScroller):
		def __init__(self,v,minsize=gPoint0,scrolldir=eScrollDefault|eScrollHideScrolls):
				ETScroller.__init__(self,v,minsize,scrolldir)
def Clipper(inner,minsize=gPoint_1,ink=gClipperBgColor):
	return ETClipper(inner,minsize,ink)

#######################################################################
class PotGuiOneOf(ETPotGuiOneOf):
	def __init__(self,slot,align=eVObjHLeft,gap=gPoint0,cr=gPoint0):
		ETPotGuiOneOf.__init__(self,slot,align,gap,cr)
class PotGuiColorSelector(ETPotGuiColorSelector):
	def __init__(self,slot,extent=gPoint16):
		ETPotGuiColorSelector.__init__(self,slot,extent)
class PotGuiPanel(ETPotGuiPanel):
	def __init__(self,gap=gPoint2,align=eVObjVExpand|eVObjHExpand,scrollersize=Point(150,200)):
		ETPotGuiPanel.__init__(self,gap,align,scrollersize)

def NoMarkButtons(f,*args,**kwds):
	"""A wrapper to create a PotGuiVObject that has no MarkButton.
 
	instead of
		PotGuiXXX(arg,arg1=x)
	write
		NoMarkButtons(PotGuiXXX,arg,arg1=x)
								^ important
	"""
 
	inb=PotGuiVObj_InAddMarkButtons()
	if inb:
		PotGuiVObj_EndAddMarkButtons()
	try:
		result=apply(f,args,kwds)
	finally:
		if inb:
			PotGuiVObj_BeginAddMarkButtons()
	return result

__classes={}
def _GetPyClass(name):
	try:
		return globals()[name+"Ptr"]
	except KeyError:
		return None

def _FindPyClassName(clptr):
	# get the class name
	cl=etguiimplc.Class_Name(clptr)
	# do we have a Ptr class in the namespace (globals)
	factory=_GetPyClass(cl)
	if not factory:
		factory=_GetPyClass("ET"+cl)
	if not factory:
		# no so, let's try the superclass
		super=etguiimplc.Class_Super(clptr)
		factory,clptr= _FindPyClassName(super)
	if type(factory) is not ClassType:
		raise TypeError
	return factory,clptr
 
def Cast(obj,cl=None):
	# get the SWIG pointer
	try:
		ptr=obj.this
	except AttributeError:
		ptr=obj
	# get the class name
	if not cl:
		cl=etguiimplc.Object_ClassName(ptr)
	# try if we already have a factory for this type
	try:
		clptr,factory=__classes[cl]
	except KeyError:
		# no, lets get the class object and search
		clptr=etguiimplc.ETMeta(cl)
		factory,clptr=_FindPyClassName(clptr)
		# add the factory to the cache
		__classes[cl]=(clptr,factory)
	return factory(DoGuard(ptr,clptr))
def SafeDelete(obj):
	ETSafeDelete(obj)
	obj.this=NULL

gSystem=Cast(gSystem)
gSysFont=Cast(gSysFont)
def SFont(fid=gSysFont.Fid(),size=gSysFont.Size(),face=gSysFont.Face(),sizedelta=0):
	size=size+sizedelta
	return etguiimplc.Font(fid,size,face)
# fonts
gFixedFont=Cast(gFixedFont)
gItalicFont=Font(
	gSysFont.Fid(),
	gSysFont.Size(),
	eFaceItalic
)
gBoldFont=Font(
	gSysFont.Fid(),
	gSysFont.Size(),
	eFaceBold
)
gBoldItalicFont=Font(
	gSysFont.Fid(),
	gSysFont.Size(),
	eFaceBold|eFaceItalic
)

#######################################################################
def ShowAlert(alertType,msg):
	return ETShowAlert(alertType,msg)
def MakeWizardDialog(pages,model,flags=None):
	if flags!=None:
		return Dialog(DoMakeWizardDialog(pages,model,flags))
	else:
		return Dialog(DoMakeWizardDialog(pages,model))
 
def ShowWizard(pages,model,flags=None):
	dialog= MakeWizardDialog(pages,model,flags)
	dialog.ShowUnderMouse()
	return dialog
def MakeDialog(pydialog):
	return Dialog(DoMakeDialog(pydialog))
def ShowDialog(pydialog):
	dialog= MakeDialog(pydialog)
	dialog.ShowUnderMouse()
	return dialog

def ShowURL(url):
	Talk("htmlviewer","show %s" %url)

#######################################################################
def ShowFileDialog(how=eFDRead,filename=None,title="Select a file"):
	wd=None
	if filename and gSystem.DirName(filename):
		wd=gSystem.WorkingDirectory()
		gSystem.ChangeDirectory(gSystem.DirName(filename))
	result=SelectFile(title,how)
	if wd is not None:
		gSystem.ChangeDirectory(wd)
	return result
def ShowDirDialog(filename=None,title="Select a directory"):
	wd=None
	if filename and gSystem.DirName(filename):
		wd=gSystem.WorkingDirectory()
		gSystem.ChangeDirectory(gSystem.DirName(filename))
	result=SelectDirectory(title)
	if wd is not None:
		gSystem.ChangeDirectory(wd)
	return result
#######################################################################
class TabSheet(ETTabSheet):
	def __init__(self,**kwds) :
		k=Kwds(kwds,single_line=0,on_top=0,items=())
		try:
			page=k.items[0]
		except IndexError:
			raise IndexError,"TabSheet:give at least one page in items!"
		ETTabSheet.__init__(self,page,k.single_line,k.on_top)
		for p in k.items[1:]:
			self.AddPage(p)
		k.Setup(self)
#######################################################################
SniffAccessError="SniffAccessError"
def SimpleSniffaccess(*args):
	import string
	arg="sniffacess "+ string.join(map(str,args)," ")
	result=ETSniffaccess(arg)
	return (int(result[0]),result[1:])
def Sniffaccess(*args):
	rc,result=apply(SimpleSniffaccess,args)
	if rc!=0:
		raise SniffAccessError,result
	return result
	
	
	
	
	
